package com.tourism.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tourism.DTO.TourRouteDTO;
import com.tourism.common.Result;
import com.tourism.entity.TourRoute;
import com.tourism.entity.TourRouteSpot;
import com.tourism.mapper.TourRouteMapper;
import com.tourism.mapper.TourRouteSpotMapper;
import com.tourism.service.TourRouteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
@Transactional
public class TourRouteServiceImpl implements TourRouteService {

    @Autowired
    private TourRouteMapper tourRouteMapper;

    @Autowired
    private TourRouteSpotMapper tourRouteSpotMapper;

    @Override
    public Result saveRoute(TourRouteDTO routeDTO) {
        if (routeDTO == null || routeDTO.getSpots() == null || routeDTO.getSpots().isEmpty()) {
            return Result.fail("路线数据不能为空");
        }

        try {
            // 1. 保存路线基本信息
            TourRoute route = new TourRoute();
            BeanUtils.copyProperties(routeDTO, route);
            route.setCreateTime(new Date());
            route.setUpdateTime(new Date());
            tourRouteMapper.insert(route);

            // 2. 保存路线景点
            for (TourRouteSpot spot : routeDTO.getSpots()) {
                spot.setRouteId(route.getId());
                tourRouteSpotMapper.insert(spot);
            }

            return Result.success("路线保存成功", route.getId());
        } catch (Exception e) {
            log.error("保存路线失败", e);
            return Result.fail("保存路线失败：" + e.getMessage());
        }
    }


    @Override
    public Result deleteRoute(Integer id) {
        if (id == null) {
            return Result.fail("路线ID不能为空");
        }

        try {
            // 1. 删除关联的景点
            QueryWrapper<TourRouteSpot> wrapper = new QueryWrapper<>();
            wrapper.eq("route_id", id);
            tourRouteSpotMapper.delete(wrapper);

            // 2. 删除路线
            tourRouteMapper.deleteById(id);

            return Result.success("路线删除成功");
        } catch (Exception e) {
            log.error("删除路线失败", e);
            return Result.fail("删除路线失败：" + e.getMessage());
        }
    }
    @Override
    public Result getRouteById(Integer id) {
        if (id == null) {
            return Result.fail("路线ID不能为空");
        }

        try {
            TourRoute route = tourRouteMapper.selectById(id);
            if (route == null) {
                return Result.fail("路线不存在");
            }

            // 获取包含景点详情的路线景点列表
            List<TourRouteSpot> spots = tourRouteSpotMapper.findByRouteIdWithSpot(id);
            TourRouteDTO routeDTO = new TourRouteDTO();
            BeanUtils.copyProperties(route, routeDTO);
            routeDTO.setSpots(spots);

            return Result.success(routeDTO);
        } catch (Exception e) {
            log.error("获取路线失败", e);
            return Result.fail("获取路线失败：" + e.getMessage());
        }
    }

    @Override
    public Result updateRoute(TourRouteDTO routeDTO) {
        if (routeDTO == null || routeDTO.getId() == null) {
            return Result.fail("路线数据不完整");
        }

        try {
            // 1. 更新路线基本信息
            TourRoute route = new TourRoute();
            BeanUtils.copyProperties(routeDTO, route);
            route.setUpdateTime(new Date());
            tourRouteMapper.updateById(route);

            // 2. 删除原有景点
            QueryWrapper<TourRouteSpot> wrapper = new QueryWrapper<>();
            wrapper.eq("route_id", route.getId());
            tourRouteSpotMapper.delete(wrapper);

            // 3. 重新保存景点
            if (routeDTO.getSpots() != null) {
                for (TourRouteSpot spot : routeDTO.getSpots()) {
                    spot.setRouteId(route.getId());
                    tourRouteSpotMapper.insert(spot);
                }
            }

            return Result.success("路线更新成功");
        } catch (Exception e) {
            log.error("更新路线失败", e);
            return Result.fail("更新路线失败：" + e.getMessage());
        }
    }
    @Override
    public Result getRouteList(Integer current, Integer size, String routeName) {
        try {
            log.info("开始获取路线列表, current: {}, size: {}, routeName: {}", current, size, routeName);

            Page<TourRoute> page = new Page<>(current, size);
            QueryWrapper<TourRoute> wrapper = new QueryWrapper<>();

            if (StringUtils.hasText(routeName)) {
                wrapper.like("route_name", routeName);
            }

            // 添加排序
            wrapper.orderByDesc("create_time");

            // 执行查询并打印SQL
            log.info("执行路线列表查询");
            Page<TourRoute> routePage = tourRouteMapper.selectPage(page, wrapper);
            log.info("查询结果: {}", routePage.getRecords());

            // 获取路线对应的景点信息
            List<TourRoute> routes = routePage.getRecords();
            for (TourRoute route : routes) {
                List<TourRouteSpot> spots = tourRouteSpotMapper.findByRouteIdWithSpot(route.getId());
                route.setSpots(spots);
            }

            return Result.success(routePage);
        } catch (Exception e) {
            log.error("获取路线列表失败", e);
            return Result.fail("获取路线列表失败: " + e.getMessage());
        }
    }


}